﻿using System;
using System.Collections.Generic;
using Wicture.DbRESTFul;

namespace Wicture.EPC.OnlineQueryProxy.Processors
{
    public class QueryContextManager
    {
        private static Dictionary<Guid, OnlineQueryContext> contexts = new Dictionary<Guid, OnlineQueryContext>();

        public static OnlineQueryContext CreateQueryContext(IQueryProcessor processor, Agents.Agent agent, QueryRequest request)
        {
            // 如果当前正在查询VIN码，不存在就创建（防止用户连续提交相同VIN的查询）
            if (!contexts.ContainsKey(request.RequestId))
            {
                var ctx = new OnlineQueryContext(processor, agent, request);
                contexts.Add(request.RequestId, ctx);
                return ctx;
            }
            else // 否则，说明用户重复提交了，不再创建请求上下文。
            {
                return null;
            }
        }

        public static void SetResult(QueryResponse response)
        {
            if (contexts.ContainsKey(response.RequestId))
            {
                var ctx = contexts[response.RequestId];
                ctx.Result = response;
                ctx.AutoResetEvent.Set();
            }
        }

        public static void Clear(OnlineQueryContext context)
        {
            if (context != null)
            {
                if (context.Agent != null) context.Agent.IsBusy = false;
                contexts.Remove(context.Request.RequestId);
            }
        }
    }
}
